<template>
  <Card class="shop">
    <p slot="title" style="font-size:20px;line-height:32px;height:32px">{{title}}</p>
    <div slot="extra" style="padding-right:32px;">
      <span v-show="type==='base'">
        <Button type="primary" size="small" @click="getStores">查询</Button>
        <Button type="primary" size="small" class="ml_5" @click="plus">新建</Button>
        <Button size="small" class="ml_5" @click="reset">重置</Button>
      </span>
      <span v-show="['plus','edit'].includes(type)">
        <Button type="primary" size="small" @click="save">保存</Button>
        <Button size="small" class="ml_5" @click="type = 'base';getStores()">返回</Button>
      </span>
    </div>
    <div v-show="type==='base'">
      <Row class="border-bottom">
        <Form ref="form" :model="address" inline label-position="left">
          <i-col>
            <FormItem label="城市" :label-width="45">
              <div class="position-msg">省</div>
              <Select v-model="address.province" style="width:100px;" @on-change="address.city = '';selectChange($event,'region','cityOption')">
                <Option v-for="(v,i) in region" :key="i" :value="v.id">{{v.name}}</Option>
              </Select>
            </FormItem>
            <FormItem :label-width="0">
              <div class="position-msg">市</div>
              <Select v-model="address.city" style="width:100px;">
                <Option v-for="(v,i) in cityOption" :key="i" :value="v.id">{{v.name}}</Option>
              </Select>
            </FormItem>

          </i-col>
        </Form>
      </Row>
      <i-table :columns="columns" :data="tableData" height="380" :loading="loading" />
      <div style="text-align: center;margin-top:20px;">
        <Page :current.sync="page" :total="total" :page-size="pageSize" show-elevator @on-change="pageChange" />
      </div>
    </div>
    <div v-show="['plus','edit'].includes(type)">
      <Form class="editForm" ref="shopForm" :model="shopForm" :rules="shopRules" label-position="left" inline>
        <Row>
          <i-col>
            <FormItem label="城市" :label-width="45">
              <div class="position-msg">省</div>
              <Select v-model="address.province" style="width:100px;" @on-change="shopForm.region = '';selectChange($event,'region','cityOption')">
                <Option v-for="(v,i) in region" :key="i" :value="v.id">{{v.name}}</Option>
              </Select>
            </FormItem>
            <FormItem prop="region" :label-width="0">
              <div class="position-msg">市</div>
              <Select v-model="shopForm.region" style="width:100px;" @on-change="toSelectShop">
                <Option v-for="(v,i) in cityOption" :key="i" :value="v.id">{{v.name}}</Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col>
            <FormItem label="门店" prop="name" :label-width="45">
              <div class="position-msg">门店</div>
              <Input v-model="shopForm.name" style="width:180px;" />
            </FormItem>
          </i-col>
        </Row>
      </Form>
    </div>
    <commonModal :visible.sync="visible" @confirm="confirm" @close="visible = false" :loading="modalLoading">
      {{disableMsg}}
    </commonModal>
  </Card>
</template>

<script>
import { getStores, createStores, updateStores, disable, enable } from 'api'
import { mapGetters } from 'vuex'
import upLoadBtn from 'components/upLoadBtn'
import { setTimeout } from 'timers'
export default {
  name: 'management',
  components: {
    upLoadBtn
  },
  computed: {
    title() {
      switch (this.type) {
        case 'base':
          return '门店管理'
          break
        case 'plus':
          return '新建'
          break
        case 'edit':
          return '编辑'
          break
        default:
          break
      }
    },
    ...mapGetters(['region', 'stores'])
  },
  data() {
    return {
      address: {
        province: '',
        city: ''
      },
      type: 'base',
      columns: [
        {
          title: '城市',
          key: 'city',
          align: 'center',
          render: (h, params) => <div>{this.renderStore(params.row)}</div>
        },
        {
          title: '门店',
          key: 'name',
          align: 'center'
        },
        {
          title: '操作',
          align: 'center',
          width: 200,
          render: (h, params) => {
            return (
              <div>
                <span
                  type="text"
                  class="span-btn"
                  onClick={() => this.tableClick('edit', params)}
                >
                  编辑
                </span>
                |
                <span
                  type="text"
                  class="span-btn dis"
                  onClick={() => this.tableClick('disable', params)}
                >
                  {params.row.is_enable ? '停用' : '启用'}
                </span>
              </div>
            )
          }
        }
      ],
      tableData: [],
      total: 60,
      shopForm: {
        name: '',
        region: '',
        is_enable: true
      },
      shopRules: {
        region: [
          {
            validator: (rule, value, callback) => {
              !value ? callback(new Error('请选择城市')) : callback()
            }
          }
        ],
        name: [
          {
            required: true,
            message: '请输入门店',
            trigger: 'blur'
          }
        ]
      },
      visible: false,
      disableMsg: '',
      uploadLoading: false,
      upLoadFile: null,
      rowParams: {},
      page: 1,
      pageSize: 20,
      cityOption: [],
      distOption: [],
      shopOption: [],
      loading: false,
      modalLoading: false
    }
  },
  created() {
    this.getStores()
  },
  methods: {
    reset() {
      this.$refs.form.resetFields()
      this.clearSelect()
      this.getStores()
    },
    plus() {
      this.$refs.shopForm.resetFields()
      this.clearSelect()
      this.type = 'plus'
    },
    tableClick(type, params) {
      this.rowParams = params.row
      switch (type) {
        case 'view':
        case 'edit':
          const storeDetail = params.row
          this.address.province = this.region.find(
            v => v.name === storeDetail.province
          ).id
          this.selectChange(this.address.province, 'region', 'cityOption')
          // this.address.city = this.cityOption.find(
          //   v => v.name === storeDetail.city
          // ).id
          // this.selectChange(this.address.city, 'cityOption', 'distOption')
          this.shopForm.region = this.cityOption.find(
            v => v.name === storeDetail.city
          ).id
          this.toSelectShop(this.shopForm.region)
          Object.keys(this.shopForm).forEach(
            key => (this.shopForm[key] = params.row[key])
          )
          this.type = type
          break
        case 'disable':
          this.disableMsg = params.row.is_enable
            ? '确定停用此门店？'
            : '确定启用此门店？'
          this.visible = true
          break
        default:
          break
      }
    },
    fileUpload(file) {
      this.upLoadFile = file
      this.manageForm.video = file.name
    },
    save() {
      this.$refs.shopForm.validate(async valid => {
        if (valid) {
          this.saveLoading = true
          let res
          switch (this.type) {
            case 'plus':
              res = await createStores(this.shopForm)
              break
            case 'edit':
              res = await updateStores({
                ...this.shopForm,
                id: this.rowParams.id
              })
              break
            default:
              break
          }
          if (res) {
            this.$Message.success(
              this.type === 'edit' ? '修改成功！' : '创建成功！'
            )
            this.$refs.shopForm.resetFields()
            this.clearSelect()
            this.type = 'base'
            this.getStores()
          }
          this.saveLoading = false
        }
      })
    },
    async confirm() {
      this.modalLoading = true
      let res
      if (this.rowParams.is_enable) {
        res = await disable({ id: this.rowParams.id }).catch(e => {
          this.visible = false
          this.$Message.error(e[0])
        })
      } else {
        res = await enable({ id: this.rowParams.id })
      }
      if (res) {
        this.getStores()
      }
      this.modalLoading = false
      this.visible = false
    },
    async getStores() {
      this.loading = true
      let res = await getStores({
        page: this.page,
        page_size: this.pageSize,
        region: this.address.city,
        region__parent: this.address.province
      })
      this.total = res.count
      this.pageSize = res.page_size
      this.page = res.page
      this.tableData = res.results
      this.loading = false
    },
    pageChange(val) {
      this.page = val
      this.getStores()
    },
    selectChange(val, key, opt) {
      if (!val) {
        return
      }
      this[opt] = this[key].find(v => v.id === val).child
    },
    clearSelect() {
      Object.keys(this.address).forEach(key => (this.address[key] = ''))
      this.shopForm.region = ''
      this.cityOption = []
      this.distOption = []
      this.shopOption = []
    },
    renderStore(store) {
      return `${store.province} ${store.city}`
    },
    toSelectShop(val) {
      if (!val) {
        return
      }
      this.shopOption = this.stores.filter(v => v.region === val)
    }
  }
}
</script>

<style lang="stylus">
.shop {
  height: 600px;
}
</style>
